<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref, UnwrapRef } from 'vue'
import {
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
  reqTrademarkList,
} from '@/api/product/trademark'
import { ElMessage } from 'element-plus'
import type { UploadProps, FormRules, FormInstance } from 'element-plus'
import type { ResponseData } from '@/api/type.ts'
import type {
  Records,
  Trademark,
  TrademarkListData,
} from '@/api/product/trademark/type.ts'

// 当前页码
const currentPage = ref<number>(1)

// 每页条数
const limit = ref<number>(10)

// 总条数
const total = ref<number>(0)

// trademark列表
const trademarkList = ref<Records>([])

// trademark表单参数
const trademarkParams = reactive<Trademark>({
  id: 0,
  tmName: '',
  logoUrl: '',
})

const dialogFormVisible = ref<boolean>(false)

const formRef = ref<FormInstance>()

const getTrademarkList = async () => {
  try {
    const { code, data, message }: ResponseData<TrademarkListData> =
      await reqTrademarkList(currentPage.value, limit.value)

    if (code === 200) {
      total.value = data?.total
      trademarkList.value = data?.records
    } else {
      ElMessage(message)
    }
  } catch (err) {
    ElMessage((err as Error).message)
  }
}

const onPageSizeChange = () => {
  currentPage.value = 1
  getTrademarkList()
}

// 点击添加品牌回调
const addTrademark = () => {
  dialogFormVisible.value = true

  // 清空数据
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''

  // 清除表单校验结果
  formRef.value?.clearValidate()
  // 第一次点击的时候，formRef还没挂载
  // nextTick(() => {
  //   formRef.value.clearValidate()
  // })
}

// 点击修改品牌回调
const updateTrademark = (row: Trademark) => {
  // trademarkParams.tmName = row.tmName
  // trademarkParams.logoUrl = row.logoUrl
  Object.assign(trademarkParams, row)
  formRef.value?.clearValidate()
  dialogFormVisible.value = true
}

const beforeLogoUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
  if (!/^image\/(jpe?g|png|gif)$/.test(rawFile.type)) {
    ElMessage.error('请上传图片，格式jpg/png/gif')
    return false
  }

  if (rawFile.size > 4 * 1024 * 1024) {
    ElMessage.error('图片太大了，不超过4M')
    return false
  }
  return true
}

const handleLogoSuccess: UploadProps['onSuccess'] = (
  response: any,
  uploadFile: any,
) => {
  trademarkParams.logoUrl = response.data
  formRef.value?.clearValidate('logoUrl')
}

// 对话框取消
const cancel = () => {
  dialogFormVisible.value = false
}

// 对话框确认
const confirm = async () => {
  try {
    await formRef.value?.validate()
  } catch (err) {
    return false
  }
  const { code, data }: ResponseData<any> =
    await reqAddOrUpdateTrademark(trademarkParams)

  if (code === 200) {
    ElMessage({
      type: 'success',
      message: `${dialogTitle.value}成功`,
    })
    currentPage.value = trademarkParams.id ? currentPage.value : 1
    await getTrademarkList()
  } else {
    ElMessage({
      type: 'error',
      message: data,
    })
  }
  dialogFormVisible.value = false
}

const deleteTrademark = async (id: number) => {
  const { code, data }: ResponseData<any> = await reqDeleteTrademark(id)

  if (code === 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })

    if (trademarkList.value.length == 1) {
      // 如果删除的数据是本页唯一一条，请求上一页数据
      currentPage.value--
    }
    await getTrademarkList()
  } else {
    ElMessage({
      type: 'error',
      message: data,
    })
  }
}

const dialogTitle = computed(() => {
  return trademarkParams.id ? '修改品牌' : '添加品牌'
})

const validatorTmName = (rule: any, value: any, callBack: any) => {
  console.log(value)
  if (value.trim().length > 1) {
    callBack()
  } else {
    callBack(new Error('品牌名称至少2个字'))
  }
}

const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('LOGO图片务必上传'))
  }
}

const rules: FormRules<Trademark> = {
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
}

onMounted(() => {
  getTrademarkList()
})
</script>
<script lang="ts">
export default {
  name: 'Trademark',
}
</script>

<template>
  <div>
    <el-card>
      <el-button
        type="primary"
        icon="Plus"
        @click="addTrademark"
        v-has="'btn.Trademark.add'"
      >
        添加品牌
      </el-button>
      <el-table :data="trademarkList" border>
        <el-table-column prop="id" label="序号" width="80"></el-table-column>
        <el-table-column prop="tmName" label="品牌名称"></el-table-column>
        <el-table-column prop="logoUrl" label="品牌logo">
          <template #default="{ row }">
            <div style="display: flex">
              <img
                :src="row?.logoUrl"
                style="height: 30px"
                alt="图片显示失败"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="edit"
              @click="updateTrademark(row)"
            ></el-button>
            <el-popconfirm
              width="250"
              icon="WarningFilled"
              :title="`确认删除品牌：${row.tmName}？`"
              confirm-button-text="确认"
              cancel-button-text="取消"
              @confirm="deleteTrademark(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="limit"
        :page-sizes="[2, 5, 10, 15, 20]"
        :small="true"
        :disabled="false"
        :background="true"
        layout="prev, pager, next, jumper, ->, total, sizes"
        :total="total"
        @current-change="getTrademarkList"
        @size-change="onPageSizeChange"
      />
    </el-card>
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle">
      <el-form
        label-width="100px"
        :rules="rules"
        :model="trademarkParams"
        ref="formRef"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            v-model="trademarkParams.tmName"
            placeholder="请输入品牌名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="logo-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :before-upload="beforeLogoUpload"
            :on-success="handleLogoSuccess"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="logo"
              alt="品牌logo图片"
            />
            <el-icon v-else class="logo-uploader-icon">
              <UploadFilled />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="scss">
.logo-uploader {
  .el-upload {
    position: relative;
    overflow: hidden;
    cursor: pointer;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.el-icon.logo-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
</style>

<style scoped lang="scss">
.el-form {
  width: 80%;
}

.logo-uploader {
  .logo {
    display: block;
    width: 178px;
    height: 178px;
  }
}
</style>
